package ulez.messagerdemo;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

/**
 * 演示messenger的用法，用于service和activity之间的通信；
 */
public class MessengerActivity extends AppCompatActivity {


    private static final String TAG = "MessengerActivity";
    private final Messenger mMessenger =new Messenger(new Messenger2Handler());

    class Messenger2Handler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MyConstants.MSG_FROM_SERVICE:
                    Log.e(TAG,"receive from service=="+msg.getData().getString("reply"));
                    break;
            }
        }
    }


    private Messenger mService;//由service生成的信使；
    private ServiceConnection conn=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService = new Messenger(service);
            Message message=Message.obtain(null,MyConstants.MSG_FROM_CLIENT);
            Bundle data=new Bundle();
            data.putString("msg","hello,this is from MessengerActivity");
            message.setData(data);
            message.replyTo=mMessenger;//这里就已经把回传的信使传入了；在service里就用回传的信使发消息；activity就能收到；
            try {
                mService.send(message);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bindService(new Intent(this,MessengerService.class),conn, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onDestroy() {
        unbindService(conn);
        super.onDestroy();
    }
}
